package cn.edu.shiep.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
@Repository
public class BaseDao< M extends Serializable,PK extends Serializable> {
	@Autowired
	private SessionFactory sessionFactory;
	
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}
	public Query createQuery(String hql) {
		return getSession().createQuery(hql);
	}
	public void save(M model) {
		getSession().save(model);
	}
	
	public void saveOrUpdate(M model) {
		getSession().saveOrUpdate(model);
	}
	
	@SuppressWarnings("unchecked")
	public M findById(PK id) {
		return (M) getSession().get(getEntityClass(),id);
	}
	
	public void update(M model) {
		getSession().update(model);
	}
	
	public void delete(M model) {
		getSession().delete(model);
	}
	
	public void deleteById(PK id) {
		getSession().delete(findById(id));
	}
	
	@SuppressWarnings("unchecked")
	public M findByExample(M model) {
		Criteria criteria = getExampleCriteria(model);
		return (M) criteria.uniqueResult();
	}
	public Criteria getExampleCriteria(M model) {
		Criteria criteria = getSession().createCriteria(this.getEntityClass())
				.add(Example.create(model));
		return criteria;
	}

	public Criteria getExampleCriteria() {
		Criteria criteria = getSession().createCriteria(this.getEntityClass());
		return criteria;
	}
	@SuppressWarnings("unchecked")
	public Class<M> getEntityClass() {
		ParameterizedType pt = (ParameterizedType) getClass().getGenericSuperclass();
		return (Class<M>) pt.getActualTypeArguments()[0];
	}
	@SuppressWarnings("unchecked")
	public List<M> findAll() {
		Criteria criteria = getSession().createCriteria(this.getEntityClass());
		return (List<M>)criteria.list();
	}
}
